PurchaseWindowCreator = Ext.extend(Ext.app.Module, {
	id : 'addPurchaseCreator',
	type : 'common/notepad',
	iarea : null,

	/**
	 * Initialize this module. This function is called at startup (page
	 * load/refresh).
	 */
	init : function(initParams) {
//alert('');
	},
	setBuyerCode : function(code) {
		this.buyerCode = code;
		this.setTitle('采购订单' + code);
		this.creator.app.getDesktop().taskbuttonTooltip = '采购订单' + code;
		this.doLayout();
	},
	/**
	 * Create this modules window here.
	 */
	createWindow : function(initParams) {

		// alert(init_buyerCode);
		var desktop = this.app.getDesktop();
		var init_buyerCode = initParams.init_buyerCode
				? initParams.init_buyerCode
				: '';
		var flag = false;

		desktop.windows.each(function(win) {
					if (win.buyerCode == init_buyerCode) {
						win.toFront();
						flag = true;
					}
				});
		if (flag) {
			return;
		}

		// this.myWindId = initParams.init_ordersId ? this.id + '_' +
		// initParams.init_ordersId : this.id;

		var versionCode = ++(PurchaseCount.count);

		var main_win = desktop.createWindow({
//					id : 'addPurchase' + versionCode,
					buyerCode : init_buyerCode,
					title : '采购订单' + init_buyerCode,
					width : 1020,
					height : 520,
					iconCls : 'acc-icon',
					animCollapse:true,
		            constrainHeader: true,
		            maximizable: true,
					taskbuttonTooltip : "采购订单",
					layout : "fit",
//					tools : [{
//								id : 'refresh',
//								handler : Ext.emptyFn,
//								scope : this
//							}],
					items : []
				});
		main_win.creator = this;
		main_win.versionCode = versionCode;
		main_win.add(this.getPanel(main_win, initParams));
		main_win.doLayout();
		main_win.show();
		desktop.addAutoRun(main_win.getId());
		// 初始化页面
		this.initPurchaseJoinPanel(main_win, initParams);
	},
	setAllHidden : function() {

		this.purchase_seller_id_hidden = new Ext.form.TextField({
					hidden : true,
					name : 'sellerId'
				});

		this.purchase_areaId_hidden = new Ext.form.TextField({
					hidden : true,
					name : 'areaId'
				});

		this.purchase_province_hidden = new Ext.form.TextField({
					hidden : true,
					name : 'province'
				});

		this.purchase_city_hidden = new Ext.form.TextField({
					hidden : true,
					name : 'city'
				});

		this.purchase_district_hidden = new Ext.form.TextField({
					hidden : true,
					name : 'district'
				});

		this.purchase_street_hidden = new Ext.form.TextField({
					hidden : true,
					name : 'street'
				});

		this.purchase_receiverName_hidden = new Ext.form.TextField({
					hidden : true,
					name : 'receiverName'
				});

		this.purchase_postCode_hidden = new Ext.form.TextField({
					hidden : true,
					name : 'postCode'
				});

		this.purchase_phone_hidden = new Ext.form.TextField({
					hidden : true,
					name : 'phone'
				});

		this.purchase_mobile_hidden = new Ext.form.TextField({
					hidden : true,
					name : 'mobile'
				});

		this.purchase_id_hidden = new Ext.form.TextField({
					hidden : true,
					name : 'id'
				});

		this.purchase_status_hidden = new Ext.form.TextField({
					hidden : true,
					name : 'status'
				});

	},
	getPurchaseItemRecord : function() {
		return Ext.data.Record.create([{
					name : 'id'
				}, {
					name : 'code'
				}, {
					name : 'sellerId'
				}, {
					name : 'name'
				}, {
					name : 'source'
				}, {
					name : 'measurementUnit'
				}, {
					name : 'brand'
				}, {
					name : 'origin'
				}, {
					name : 'price'
				}, {
					name : 'price'
				}, {
					name : 'orderQuantity'
				}, {
					name : 'level1Id'
				}, {
					name : 'partId'
				}, {
					name : 'level1Name'
				}, {
					name : 'level2Name'
				}, {
					name : 'partCategoryId'
				}, {
					name : 'durability'
				}, {
					name : 'inventoryIdBySeller'
				}, {
					name : 'exec'
				}]);

	},
	getPurchaseItemStore : function() {
		return new Ext.data.JsonStore({
					url : PUR_QUERY_URL,
					baseParams : {},
					mode : "local",
					totalProperty : "results",
					root : "purchaseDetails",
					idProperty : "id",
					pruneModifiedRecords : true,
					fields : this.purchase_item_record
				});

	},
	setAllCmb : function() {

		// 区县下拉框
		this.dist_cmb = getDistrictCombox(RES_PATH, this.purchase_areaId_hidden);// dist_cmb.setWidth(80);
		this.dist_cmb.hiddenName = null;
		this.dist_cmb.name = 'district';
		// 城市下拉框
		this.city_cmb = getCityCombox(RES_PATH, this.dist_cmb,
				this.purchase_areaId_hidden);
		this.city_cmb.hiddenName = null;
		this.city_cmb.name = 'city';
		// 省份下拉框
		this.prov_cmb = getProvinceCombox(RES_PATH, this.city_cmb,
				this.dist_cmb, this.purchase_areaId_hidden);
		this.prov_cmb.hiddenName = null;
		this.prov_cmb.name = 'province';

		// 如果要显示效验信息则必需
		Ext.QuickTips.init();

		// turn on validation errors beside the field globally
		Ext.form.Field.prototype.msgTarget = 'side';

		// 支付方式下拉框
		this.payType_store = getDictionaryStore(RES_PATH, {
					group : 'payType'
				});
		this.payType_cmb = getDictionaryComboBox(this.payType_store, 'remote',
				'paymentType', '支付方式', null, 100);

		// 运输方式下拉框
		this.transportType_store = getDictionaryStore(RES_PATH, {
					group : 'transportType'
				});
		this.transportType_cmb = getDictionaryComboBox(
				this.transportType_store, 'remote', 'transportType', '运输方式',
				null, 100);

		// 来源下拉框
		this.sourceType_store = getDictionaryStore(RES_PATH, {
					group : 'part_source'
				});
		this.source_cmb = getDictionaryComboBox(this.sourceType_store, 'local',
				'part_source', '来源', 'source');
		// source_cmb.id = '_source';

	},
	getPartnerCombox : function() {
		/**
		 * 供应商查询store
		 */
		var ds_partner_store = new Ext.data.JsonStore({
					url : PurchaseUrl.PUR_FIND_PARTNER_BY_CODE_URL,
//					id : "id",
					root : 'root',
					totalProperty : 'totalProperty',
					remoteSort : true,
					baseParams:{start:0,limit:4,type:1},
					fields : [{
								name : 'id',
								type : 'int'
							}, {
								name : 'pyCode',
								type : 'string'
							}, {
								name : 'name',
								type : 'string'
							}, {
								name : 'companyId',
								type : 'int'
							}]
				});
		/**
		 * 供货商combox
		 */
		return new Ext.form.LookupBox2({
			store : ds_partner_store,
			// fieldLabel : '供货单位',
//			name : 'sellerName',
//			id : "sellerName",
			displayField : 'name',
			lookupField : 'pyCode',
			valueField : 'id',
			hiddenId : 'partnerIdByBuyer' + new Date().getTime(),
			hiddenName : 'partnerIdByBuyer',
			typeAhead : false,
			mode : 'local',
			// tpl : '<tpl for="."><div ext:qtip="{pyCode}. {name}"
			// class="x-combo-list-item">{pyCode}. {name}</div></tpl>',
			triggerAction : 'all',
			emptyText : '输入拼音或名字查询供货商..',
			selectOnFocus : true,
			// applyTo : 'partner_lookup_combox',
			queryParam : 'queryParam',
			queryDelay : 10,
			typeAheadDelay : 10,
			pageSize : 4,
			lookupCallBackEvents:['lookupChange'],
			start : 0,
			anchor : '100%',
			width : 318,
			// autoDestory : true,
			app : this.creator.app,
			triggerTags : [{moduleId: 'partner_query', params : {partnerType : 1}, triggerClass:'x-form-search-trigger'},{moduleId:'partner_add'}],
			listeners : {
				'select' : function() {
//					var partnerId = this.partner_combox.getValue();	
//					this.purchase_seller_id_hidden.setValue(ds_partner_store.getById(partnerId).data.companyId);
//					this.address_combox.triggerTags[0].params={partnerId:partnerId};
//					this.address_combox.triggerTags[1].params={partnerId:partnerId};
				}.createDelegate(this)
				,
				'lookupChange' : function(record) {
//					var partnerId = this.partner_combox.getValue();	
//					this.purchase_seller_id_hidden.setValue(record.data.companyId);
//					this.address_combox.triggerTags[0].params={partnerId:partnerId};
//					this.address_combox.triggerTags[1].params={partnerId:partnerId};
				}.createDelegate(this)
					
			}
		});
	},
	validateSellerIsNotNull : function() {
		var partnerIdByBuyer = this.partner_combox.getValue();
//		 alert(partnerIdByBuyer);
		if ( !partnerIdByBuyer ) {
			Ext.Msg.alert(PurChaseAlert.PROMOTE_ERROR, '供应商不能为空...');
			return false;
		}
		return true;
	},
	/**
	 * 全部回到空状态
	 */
	resetAll : function() {
		// alert(this.main_win.getId());
		this.creator.setBuyerCode.createDelegate(this, [''])();
		this.purchase_panel.getForm().reset();
		this.purchase_item_store.removeAll();

		// this.purchase_panel.getForm().el.dom.reset();
	},
	/**
	 * 修改数据前的数据收集
	 */
	getModifyData : function() {
		var obj = {};
		obj.all = [];
		obj.add = [];
		obj.update = [];
		this.purchase_item_store.each(function(rec) {
					if (rec.data.id) {
						obj.all.push(rec.data.id);
					} else {
						obj.add.push(rec.data);
					}
				});
		var update = this.purchase_item_store.getModifiedRecords();
		Ext.each(update, function(rec) {
					if (rec.data.id) {
						obj.update.push(rec.data);
					}
				});
		// obj.update = getProDataObjs(obj.update);
		return obj;
	},
	createNewPurButtons : function(panel, btns, id) {
		var btnFieldset = new Ext.Panel({
					border : false,
					id : id + panel.main_win.versionCode,
					layout : 'hbox',
					height : 30,
					layoutConfig : {
						align : 'top',
						pack : 'center'
					},
					defaults : {
						margins : '0 10',
						buttonAlign : 'center',
						width : 70,
						height : 25
					}
				});

		panel.add(btnFieldset);
		panel.doLayout(true);

		var ref = panel.main_win;
		for (var i = 0; i < btns.length; i++) {
			var obj = btns[i];
			var btn = new Ext.Button({
						id : obj.id + ref.versionCode,
						text : obj.value,
						width : 120,
						height : 22,
						url : RES_PATH + obj.url,
						func : obj.func,
						alertMeses : obj.alertMeses,
						tooltip : obj.tips,
						tooltipType : 'qtip',
						handler : function(bn) {
//							 alert(bn==this); ->is true
							bn.main_win = ref;
							eval('bn.main_win.creator.' + bn.func).createDelegate(bn)();
						}
					});

			btnFieldset.add(btn);
			btnFieldset.doLayout(true);
		}
	},
	/**
	 * 判断采购记录是否已经被选中
	 * 
	 * @param {}
	 *            flag
	 * @return {Boolean}
	 */
	validatePur : function(flag) {
		var records = this.purchase_item_store.getRange();
		for (var i = 0; i < records.length; i++) {
			var rec = records[i];
			if (rec.data.code + rec.data.source == flag) {
				Ext.Msg.alert(PurChaseAlert.PROMOTE_ERROR, '该记录已经被选择...');
				return false;
			}
		}
		return true;
	},
	/**
	 * 根据报价信息记录设置每条采购记录属性值
	 * 
	 * @param {}
	 *            _record
	 * @return {}
	 */
	getPurRecord : function(_record) {
		var data = _record.data
		var purData = {};
		purData.orderQuantity = 1;

		purData.name = data.name;
		purData.code = data.code;
		purData.source = data.source;
		purData.measurementUnit = data.measurementUnit;
		purData.brand = data.brand;
		purData.origin = data.origin;
		purData.price = data.retailPrice;
		purData.level1Name = data.level1Name;
		purData.level2Name = data.level2Name;
		purData.level1Id = data.level1Id;
		purData.partId = data.partId;
		purData.partCategoryId = data.partCategoryId;
		purData.durability = data.durability;
		purData.inventoryIdBySeller = data.inventoryIdBySeller;
		var record = new this.purchase_item_record(purData);
//		record.id = _record.id;
//		purData.sellerId = data.companyId;
		this.purchase_seller_id_hidden.setValue(data.companyId);
		return record;
	},
	getQuotationItemGrid : function() {

		var scmb = {};
		scmb.source_cmb = this.source_cmb;
		// 定义报价单grid表头
		var quotation_item_colName = new Ext.grid.ColumnModel([{
					header : '零件编码',
					dataIndex : 'code'
				}, {
					header : '零件名称',
					dataIndex : 'name'
				}, {
					header : '来源',
					dataIndex : 'source',
					renderer : getSourceName.createDelegate(scmb)
//					editor : this.source_cmb
				}, {
					header : '单位',
					dataIndex : 'measurementUnit'
				}, {
					header : '品牌',
					dataIndex : 'brand',
					sortable : true
				}, {
					header : '产地',
					dataIndex : 'origin',
					sortable : true
				}, {
					header : '媒体价',
					dataIndex : 'retailPrice'
				}, {
					header : '操作',
					dataIndex : 'exec',
					renderer : createAddQuotaBtn.createDelegate(this)
				}]);

		function createAddQuotaBtn(value, metadata, record, rowIndex, colIndex,
				store) {

			return '<div><a id="' + QUO_BUY_REOCRD_ID + record.data.id
					+ this.versionCode + '" href="#">订购</a></div>';
		}

		// 创建grid，装载明细数据
		return new Ext.grid.GridPanel({
//					title : '报价信息',
					id : 'quotation_item_grid_id' + this.versionCode,
					cm : quotation_item_colName,
					store : this.quotation_item_store,
					style : {padding : '2px'},
					iconCls : 'icon-grid',
					loadMask : {
						msg : '数据加载中...'
					},
					viewConfig : {
						forceFit : true
					},
					// width : 950,
					height : 150,
					// autoHeight : true,
					bbar : new Ext.PagingToolbar({
								pageSize : 2,
								store : this.quotation_item_store,
								displayInfo : true,
								displayMsg : '第 {0} - {1} 条  共 {2} 条',
								emptyMsg : "没有记录"

							})
				});

	},
	getQuotationItemStore : function() {

		// 报价单
		var quotation_item_record = Ext.data.Record.create([{
					name : 'id'
				}, {
					name : 'code'
				}, {
					name : 'name'
				}, {
					name : 'companyId'
				}, {
					name : 'source'
				}, {
					name : 'measurementUnit'
				}, {
					name : 'brand'
				}, {
					name : 'origin'
				}, {
					name : 'retailPrice'
				}, {
					name : 'exec'
				}, {
					name : 'partId'
				}, {
					name : 'level1Name'
				}, {
					name : 'level2Name'
				}, {
					name : 'level1Id'
				}, {
					name : 'partCategoryId'
				}, {
					name : 'durability'
				}, {
					name : 'inventoryIdBySeller'
				}]);

		return new Ext.data.Store({

					proxy : new Ext.data.HttpProxy({
								url : QUOTA_QUREY_URL,
								method : 'post'
							}),
					pruneModifiedRecords : true,
					paramNames : {
						start : "start",
						limit : "limit"
					},
					remoteSort : true,
					// baseParams : {code : '001'},
					reader : new Ext.data.JsonReader({
								totalProperty : 'totalProperty',
								root : 'root'
							}, quotation_item_record)
				});

	},
	getQuotationFormItem1 : function() {
		return {

			style : 'padding:0px;fontSize:13px;',
			layout : 'hbox',
			width : 1010,
			heigth : 80,
			items : [

			{
						xtype : 'label',
						text : '编码:',
						style : {
							marginLeft : '1px',
							width : '50px'
						}
					}, {
						xtype : 'textfield',
						name : 'code',
						// id : 'code',
						style : {
							width : '90px'
						}
					}, {
						xtype : 'label',
						text : '名称:',
						style : {
							marginLeft : '20px',
							width : '65px'
						}
					}, {
						xtype : 'textfield',
						name : 'name',
						// id : 'name',
						style : {
							width : '90px'
						}
					}, {
						xtype : 'label',
						text : '来源:',
						style : {
							marginLeft : '20px',
							width : '65px'
						}
					}, this.source_cmb, {
						xtype : 'label',
						text : '品牌:',
						style : {
							marginLeft : '20px',
							width : '65px'
						}
					}, {
						xtype : 'textfield',
						name : 'brand',
						// id : 'brand',
						style : {
							width : '90px'
						}
					}, {
						xtype : 'label',
						text : '产地:',
						style : {
							marginLeft : '20px',
							width : '65px'
						}
					}, {
						xtype : 'textfield',
						name : 'origin',
						// id : 'origin',
						style : {
							width : '90px'
						}
					}, {
						xtype : 'button',
						text : '查    找',
						width : 60,
						style : {
							marginLeft : '30px'
						},
						listeners : {
							click : function() {

								if (!this.creator.validateSellerIsNotNull.createDelegate(this)()) {
									return;
								}

								var values = this.quotation_panel.getForm()
										.getValues();
								values = castNoSelToNULL(values);
								this.quotation_item_store.baseParams = values;
								if (!this.partner_combox.getValue()
										|| (this.partner_combox.getValue() + '')
												.trim() == '') {
									Ext.Msg.alert(PurChaseAlert.PROMOTE_ERROR,
											"供货单位未选择...");
									return;
								}

								this.quotation_item_store.baseParams.partnerIdByBuyer = this.partner_combox
										.getValue();

								this.quotation_item_store.load();
								this.quotation_item_store.baseParams = {};
							}.createDelegate(this)
						}

					}]
		};

	},
	getPurchaseItemColName : function() {

		function createDelPurBtn(value, metadata, record, rowIndex, colIndex,
				store) {
//			alert(record.id);
			return '<div><a id="' + PUR_DEL_RECORD_ID + record.id
					+ this.versionCode + '" href="#">删除</a></div>';
		}

		// 定义grid表头
		return new Ext.grid.ColumnModel([{
					header : '零件编码',
					dataIndex : 'code'
				}, {
					header : '零件名称',
					dataIndex : 'name'
				}, {
					header : '来源',
					dataIndex : 'source',
					renderer : Ext.util.Format.comboRenderer(this.source_cmb)
//					editor : this.payType_cmb
				}, {
					header : '单位',
					dataIndex : 'measurementUnit'
				}, {
					header : '品牌',
					dataIndex : 'brand',
					sortable : true
				}, {
					header : '产地',
					dataIndex : 'origin',
					sortable : true
				}, {
					header : '媒体价',
					dataIndex : 'price'
				}, {
					header : '订购价',
					dataIndex : 'price'
				}, {
					header : '订购数量',
					dataIndex : 'orderQuantity',
					editor : new Ext.form.TextField({
								regex : /^[0-9]*$/,
								regexText : '只能够输入数字'
							})
				}, {
					header : '操作',
					dataIndex : 'exec',
					renderer : createDelPurBtn.createDelegate(this)
				}]);

	},

	getAddressCombox : function() {

		var ds_address_store = new Ext.data.JsonStore({
//					url : Uec3.App.Constants.homeUrl
//							+ "/receiptAddress/edit_receiptAddress!query.do",
//					id : "id",
//					root : 'root',
//					totalProperty : 'totalProperty',
//					remoteSort : true,
//					baseParams : {
//						sort : 'id',
//						dir : 'ASC'
//					},
					fields : [{
								name : 'areaId',
								type : 'string'
							}, {
								name : 'province',
								type : 'string'
							}, {
								name : 'city',
								type : 'string'
							}, {
								name : 'district',
								type : 'string'
							}, {
								name : 'street',
								type : 'string'
							}, {
								name : 'postCode',
								type : 'string'
							}, {
								name : 'receiverName',
								type : 'string'
							}, {
								name : 'phone',
								type : 'string'
							}, {
								name : 'mobile',
								type : 'string'
							}, {
								name : 'address',
								type : 'string'
							}],
					listeners : {
						'beforeload' : function(store, options) {

						},
						'load' : function(store, records, options) {
							Ext.each(records, function(record, index, array) {
										var address = record.data.province
												+ record.data.city
												+ record.data.district
												+ record.data.street;
										record.set('address', address);
									});
						}
					}
				});

		return new Ext.form.LookupBox2({
			store : ds_address_store,
			// fieldLabel : '收货地址',
//			name:'areaId',
			displayField : 'address',
			lookupField : 'areaId',
			valueField : 'areaId',
			typeAhead : false,
			mode : 'local',
			// tpl : '<tpl for="."><div ext:qtip="{pyCode}. {name}"
			// class="x-combo-list-item">{pyCode}. {name}</div></tpl>',
			triggerAction : 'all',
			emptyText : '选择收货地址..',
			selectOnFocus : true,
			// applyTo: 'partner_lookup_combox',
//			queryParam : 'queryParam',
//			queryDelay : 10,
//			typeAheadDelay : 10,
//			pageSize : 4,
//			start : 0,
			lookupCallBackEvents:['lookupChange'],
			width : 400,
			anchor : '100%',
			editable : false,
			app : this.creator.app,
//            autoDestory:true,
            triggerTags : [{moduleId:'receiptAddressQuery',triggerClass:'x-form-search-trigger'},{moduleId:'receiptAddressAdd'}],	
			listeners : {
				'lookupChange' : this.creator.fillPartnerAddressInfo.createDelegate(this)
			}
		});

	},

	/**
	 * 根据所选地址自动填充供货商地址、邮编、联系人等信息
	 */
	fillPartnerAddressInfo : function(record) {
//		 alert(this.purchase_panel);
		var fieldNames = ['areaId', 'province', 'city', 'district', 'street',
				'postCode', 'receiverName', 'phone', 'mobile'];
		Ext.each(fieldNames, function(fieldName, index, array) {
			if(record.data) {
				this.purchase_panel.getForm().findField(fieldName).setValue(record.data[fieldName]);
			} else {
				this.purchase_panel.getForm().findField(fieldName).setValue(record[fieldName]);
			}
		}.createDelegate(this));
	},
	getPurchasePanel : function() {

		var pur_formReader = new Ext.data.JsonReader({
			root : ""
				// totalProperty : 'totalProperty'
			}, [{
					name : 'id'
				}, {
					name : 'codeOfBuyer'
				}, {
					name : 'sellerId'
				}, {
					name : 'areaId'
				}, {
					name : 'sellerName'
				}, {
					name : 'memoOfBuyer'
				}, {
					name : 'street'
				}, {
					name : 'receiverName'
				}, {
					name : 'postCode'
				}, {
					name : 'phone'
				}, {
					name : 'mobile'
				}, {
					name : 'province'
				}, {
					name : 'city'
				}, {
					name : 'district'
				}, {
					name : 'paymentType'
				}, {
					name : 'transportType'
				}, {
					name : 'statusDes'
				}, {
					name : 'status'
				}, {
					name : 'creator'
				}, {
					name : 'gmtCreate'
				}, {
					name : 'submitter'
				}, {
					name : 'gmtSubmit'
				}, {
					name : 'amount'
				}, {
					name : 'pyCode'
				}, {
					name : 'partnerName'
				}, {
					name : 'partnerIdByBuyer'
				}
			]);

		// 采购订单主表头信息1
		var purchase_form_item1 = new Ext.form.FieldSet({
					// xtype : 'panel',
					// title : '采购订单',

					items : [
						{
						style : 'padding:0px;fontSize:13px;',
						layout : 'hbox',
						// width : '95%',
						height : 20,
						layoutConfig : {
							padding : 0,
							// margins:10,
							align : 'middle'
						},
						items : [{
									xtype : 'spacer',
									flex : 1
								}, {
									xtype : 'label',
									text : '采购订单',
									style : {
										font : 'bold 18px arial, serif'
									}
								}, {
									xtype : 'spacer',
									flex : 1
								}, {
									xtype : 'label',
									text : '单据号:',
									style : {
										fontSize : '13px'
									}
								}, {
									xtype : 'textfield',
									name : 'codeOfBuyer',
									style : PurchaseColor.READ_ONLY_COLOR
											+ "; width : 100px",
									readOnly : true
								}]
					}

					, {
						html : '<hr color="#34A4E0" />'
					}, {
						style : 'padding:0px;fontSize:13px;',
						layout : 'hbox',
						// width : '95%',
						height : 30,
						layoutConfig : {
							padding : 1,
							// margins:10,
							align : 'middle'
						},
						items : [{
									xtype : 'label',
									text : '供货单位:  ',
									style : {
										marginLeft : '1px',
										width : '81px'
									}
								}, this.partner_combox,
								this.purchase_id_hidden,
								this.purchase_seller_id_hidden,
								this.purchase_areaId_hidden,
								this.purchase_province_hidden,
								this.purchase_city_hidden,
								this.purchase_district_hidden,
								this.purchase_street_hidden,
								this.purchase_receiverName_hidden,
								this.purchase_postCode_hidden,
								this.purchase_phone_hidden,
								this.purchase_mobile_hidden,
								this.purchase_status_hidden, {
									xtype : 'label',
									text : '备  注:  ',
									style : {
										marginLeft : '40px',
										width : '120px'
									}
								}, {
									xtype : 'textarea',
									name : 'memoOfBuyer',
									style : {
										height : '30px',
										width : '390px'
									}
								}]
					}, {
						style : 'padding:0px;fontSize:13px;',
						layout : 'hbox',
						// width : '95%',
						height : 25,
						layoutConfig : {
							padding : 1,
							// margins:10,
							align : 'middle'
						},
						items : [{
									xtype : 'label',
									text : '支付方式:  ',
									style : {
										marginLeft : '1px',
										width : '80px'
									}
								}, this.payType_cmb, {
									xtype : 'label',
									text : '运输方式:  ',
									style : {
										marginLeft : '40px',
										width : '120px'
									}
								}, this.transportType_cmb, {
									xtype : 'label',
									text : '收货地址:  ',
									style : {
										marginLeft : '40px',
										width : '120px'
									}
								}, this.address_combox]
					}]
				});

		// 采购订单主表头信息2
		var purchase_form_item2 = {
			style : 'padding:0px; fontSize:13px; marginTop:3px',
			layout : 'hbox',
			// width : '95%',
			height : 30,
			items : [{
						xtype : 'label',
						text : '单据状态:',
						style : {
							marginLeft : '1px',
							width : '70px'
						}
					}, {
						xtype : 'textfield',
						name : 'statusDes',
						style : PurchaseColor.READ_ONLY_COLOR
								+ "; width : 100px",
						readOnly : true
					}, {
						xtype : 'label',
						text : '创建人:',
						style : {
							marginLeft : '5px',
							width : '60px'
						}
					}, {
						xtype : 'textfield',
						name : 'creator',
						style : PurchaseColor.READ_ONLY_COLOR
								+ "; width : 80px",
						readOnly : true
					}, {
						xtype : 'label',
						text : '创建时间:',
						style : {
							marginLeft : '5px',
							width : '70px'
						}
					}, {
						xtype : 'textfield',
						name : 'gmtCreate',
						style : PurchaseColor.READ_ONLY_COLOR
								+ "; width : 90px",
						readOnly : true
					}, {
						xtype : 'label',
						text : '提交人:',
						style : {
							marginLeft : '5px',
							width : '60px'
						}
					}, {
						xtype : 'textfield',
						name : 'submitter',
						style : PurchaseColor.READ_ONLY_COLOR
								+ "; width : 80px",
						readOnly : true
					}, {
						xtype : 'label',
						text : '提交时间:',
						style : {
							marginLeft : '5px',
							width : '70px'
						}
					}, {
						xtype : 'textfield',
						name : 'gmtSubmit',
						style : PurchaseColor.READ_ONLY_COLOR
								+ "; width : 90px",
						readOnly : true
					}, {
						xtype : 'label',
						text : '总金额:',
						style : {
							marginLeft : '5px',
							width : '60px'
						}
					}, {
						xtype : 'textfield',
						// id : 'pur_amount',
						name : 'amount',
						style : PurchaseColor.READ_ONLY_COLOR
								+ "; width : 90px",
						readOnly : true
					}]
		};

		// 表单数据
		return new Ext.FormPanel({
					// labelAlign : 'right',
					// frame : true,
					height : 300,
					// autoWidth : true,
					// autoScroll : false,
					reader : pur_formReader,
					items : [purchase_form_item1, this.purchase_item_grid,
							purchase_form_item2]
				});

	},
	getQuotationPanel : function() {

		// 报价面板
		return new Ext.FormPanel({
					// labelAlign : 'right',
					frame : true,
					height : 180,
					// autoWidth : true,
					// autoScroll : true,

					items : [this.quotation_form_item1,
							this.quotation_item_grid]
				});

	},
	/**
	 * 初始加载
	 */
	initPurchaseJoinPanel : function(main_win, initParams) {
		// quotation_panel.hide();

		main_win.sourceType_store.load();
//alert(initParams.init_ordersId);
		if (initParams && initParams.init_ordersId) {
			var tmp = {};
			tmp.url = PUR_TO_SHOW_URL;
			tmp.main_win = main_win;
			tmp.alertMeses = {
				'ordersOk' : PurChaseAlert.PROMOTE_OK + ':订单查询成功',
				'ordersNotCurrentUser' : PurChaseAlert.PROMOTE_OK
						+ ':订单查询成功，但您不是当前处理人',
				'ordersSubmit' : PurChaseAlert.PROMOTE_OK + ':订单查询成功，但该单据已被提交',
				'ordersNotExist' : PurChaseAlert.PROMOTE_ERROR
						+ ':订单查询失败,该单据不存在或已被删除',
				'ordersError' : PurChaseAlert.PROMOTE_ERROR + ':订单查询失败'
			};

			this.sendDataAndGetMes.createDelegate(tmp, [{
						status : initParams.init_status,
						ordersId : initParams.init_ordersId
					}, true])();

			initParams.init_ordersId = undefined;
			initParams.init_status = undefined;

		} else {
			var tmp = {};
			tmp.url = PUR_TO_CREATE_URL;
			tmp.main_win = main_win;
			this.sendDataAndGetMes.createDelegate(tmp, [null, true])();

		}

	},
	// f4
	callbackAlertFunc : function() {

		if (this.vo.load_num == 1) {
			if (this.loadBtns) {
				if (this.loadMask) {
					this.loadMask.hide();
				}
				if (this.vo.pur_alert_mes) {
					var alerts = this.alertMeses[this.vo.pur_alert_mes]
							.split(':');
					if(!this.vo.ordersId && this.vo.remove != '0') {
						Ext.Msg.alert(alerts[0], alerts[1], function() {
							this.close();
						}.createDelegate(this.main_win));
					} else {
						Ext.Msg.alert(alerts[0], alerts[1]);
					}
				}
//				if (!this.vo.ordersId && this.vo.remove != '0') {
//					this.main_win.creator.resetAll.bind(this.main_win)();
//				}
				if (this.vo.ordersId) {
					this.main_win.creator.addRemovePurItemRecordEvent.createDelegate(this.main_win)();
					this.main_win.creator.setBuyerCode.createDelegate(this.main_win,
							[this.main_win.purchase_panel.getForm()
									.findField('codeOfBuyer').getValue()])();
				} else {
					this.main_win.creator.setBuyerCode.createDelegate(this.main_win, [''])();
				}
			}
		} else if (this.vo.load_num == 3) {
			if (this.loadForm && this.loadGrid && this.loadBtns) {
				if (this.loadMask) {
					this.loadMask.hide();
				}
				if (this.vo.pur_alert_mes) {
					var alerts = this.alertMeses[this.vo.pur_alert_mes]
							.split(':');
					if(!this.vo.ordersId && this.vo.remove != '0') {
						Ext.Msg.alert(alerts[0], alerts[1], function() {
							this.close();
						}.createDelegate(this.main_win));
					} else {
						Ext.Msg.alert(alerts[0], alerts[1]);
					}
				}
//				if (!this.vo.ordersId && this.vo.remove != '0') {
//					this.main_win.creator.resetAll.bind(this.main_win)();
//				}
				if (this.vo.ordersId) {
					this.main_win.creator.addRemovePurItemRecordEvent.createDelegate(this.main_win)();
					this.main_win.creator.setBuyerCode.createDelegate(this.main_win,
							[this.main_win.purchase_panel.getForm()
									.findField('codeOfBuyer').getValue()])();
				} else {
					this.main_win.creator.setBuyerCode.createDelegate(this.main_win, [''])();
				}
			}
		} else {
			if (this.loadMask) {
				this.loadMask.hide();
			}
			if (this.vo.pur_alert_mes) {
				var alerts = this.alertMeses[this.vo.pur_alert_mes].split(':');
				if(!this.vo.ordersId && this.vo.remove != '0') {
					Ext.Msg.alert(alerts[0], alerts[1], function() {
						this.close();
					}.createDelegate(this.main_win));
				} else {
					Ext.Msg.alert(alerts[0], alerts[1]);
				}
			}
			if (this.vo.ordersId) {
				this.main_win.creator.addRemovePurItemRecordEvent.createDelegate(this.main_win)();
				this.main_win.creator.setBuyerCode.createDelegate(this.main_win,
						[this.main_win.purchase_panel.getForm()
								.findField('codeOfBuyer').getValue()])();
			} else {
				this.main_win.creator.setBuyerCode.createDelegate(this.main_win, [''])();
			}
		}

	},
	// f1
	loadPurForm : function(params) {
//		alert(this.main_win.purchase_panel.getForm().load);
		this.main_win.purchase_panel.getForm().load({
					url : PUR_QUERY_BY_ID_URL,
					params : params ? params : {
						ordersId : this.vo.ordersId
					},
					success : function(form, action) {
						// if(purchase_id_hidden.getValue()) {
						// resetAll();
						// }
						// loadProvCityDistComb(purchase_areaId_hidden.getValue(),
						// prov_cmb, city_cmb, dist_cmb);
						
//						console.debug(action);
						
//						alert(this.main_win.partner_combox);
						
						
						this.main_win.address_combox.initializeValue({
							'areaId' : action.result.data.areaId,
							'address' : action.result.data.province
									 + action.result.data.city
									 + action.result.data.district
									 + action.result.data.street
									 + "," + action.result.data.receiverName
									 + "," + action.result.data.phone
									 + "," + action.result.data.mobile
						});
						
						this.main_win.partner_combox.initializeValue({
							'name' : action.result.data.partnerName,
							'pyCode' : action.result.data.pyCode,
							'id' : action.result.data.partnerIdByBuyer
						});
							
						this.loadForm = true;
						this.main_win.creator.callbackAlertFunc.createDelegate(this)();
					}.createDelegate(this)
				});
	},

	// f2
	loadDetailsGrid : function(params) {
		this.main_win.purchase_item_store.load({
					params : params ? params : {
						ordersId : this.vo.ordersId
					},
					callback : function() {
						this.loadGrid = true;
						this.main_win.creator.callbackAlertFunc.createDelegate(this)();
//						this.main_win.creator.addRemovePurItemRecordEvent
//								.bind(this.main_win)();
					}.createDelegate(this)
				});
	},

	// f3
	loadButtonsToolBar : function(params) {

		this.main_win.creator.removeButtonFieldSetFromPanel(
				this.main_win.join_panel, PUR_BUTTON_FDSET_ID);
		Ext.Ajax.request({
			url : PUR_LOAD_BUTNS_URL,
			params : params ? params : {
				status : this.vo.status,
				ordersId : this.vo.ordersId
			},
			success : function(data) {
				var bo = Ext.decode(data.responseText);

				if (bo.disa == '1') {
					this.main_win.purchase_panel.disable();
					if(this.main_win.quotation_panel) {
						this.main_win.quotation_panel.disable();
					}
				} else {
					this.main_win.purchase_panel.enable();
					if(this.main_win.quotation_panel) {
						this.main_win.quotation_panel.enable();
					}
				}

				this.main_win.creator.createNewPurButtons(
						this.main_win.join_panel, bo.btns, PUR_BUTTON_FDSET_ID);
				this.loadBtns = true;
				this.main_win.creator.callbackAlertFunc.createDelegate(this)();
			}.createDelegate(this)
		});
	},

	/**
	 * 点击按钮发送和回显(共用方法)
	 */
	sendDataAndGetMes : function(params, notLoadedMask) {
		// alert(this.wind);
		if (!notLoadedMask) {
			this.loadMask = new Ext.LoadMask(this.main_win.getId(), {
						removeMask : true,
						msg : '数据传送中......'
					});
			// this.loadMask.enable();
			this.loadMask.show();
		}
		Ext.Ajax.request({
					url : this.url,
					params : params,
					success : function(data) {
						var vo = Ext.decode(data.responseText);
						this.vo = vo;
						if (!this.vo.loadedMesesKeys)
							return;
						var load_funcs_keys = this.vo.loadedMesesKeys
								.split(':');
						this.vo.load_num = load_funcs_keys.length;
						if (this.vo.load_num == 1
								&& load_funcs_keys[0] == 'callbackAlertFunc') {
							this.vo.load_num = 0;
						}
						Ext.each(load_funcs_keys, function(func_key_str) {
									eval('this.main_win.creator.'
											+ func_key_str).createDelegate(this)();
								}.createDelegate(this));
					}.createDelegate(this)
				});
	},

	sumAmount : function() {
		var recs = this.purchase_item_store.getRange();

		var amount = 0.0;

		Ext.each(recs, function(rec) {
					amount += Ext.util.Format.number(rec.data.price)
							* Ext.util.Format.number(rec.data.orderQuantity);
				});
		amount = Ext.util.Format.number(amount, '0.00');
		this.purchase_panel.getForm().findField('amount').setValue(amount);
	},
	/**
	 * 删除采购订单行记录
	 * 
	 * @param {}
	 *            id
	 * @param {}
	 *            code
	 * @param {}
	 *            source
	 */
	purchaseDelRow : function(record) {

		this.purchase_item_store.remove(record);

	},

	addRemovePurItemRecordEvent : function() {
		var recs = this.purchase_item_store.getRange();
		var ref = this;
		Ext.each(recs, function(rec) {
			rec.main_win = ref;
			var obj = Ext.get(PUR_DEL_RECORD_ID + rec.id + ref.versionCode);
			obj.on('click', function() {
				this.main_win.creator.purchaseDelRow.createDelegate(this.main_win, [this])();
			}.createDelegate(rec));
		});
	},
	addEventToPurItemGrid : function() {

		Ext.util.Observable.capture(this.purchase_item_grid.getView(),
				function(e) {
					if (e == 'rowsinserted' || e == 'rowupdated'
							|| e == 'rowremoved') {
						// 计数
						this.creator.sumAmount.createDelegate(this)();
						this.creator.addRemovePurItemRecordEvent.createDelegate(this)();
					}
				}.createDelegate(this));
	},
	/**
	 * 面板上移除fieldset
	 * 
	 * @param {}
	 *            panel
	 * @param {}
	 *            fdsetId
	 */
	removeButtonFieldSetFromPanel : function(panel, fdsetId) {
		panel.remove(fdsetId + panel.main_win.versionCode, true);
	},
	/**
	 * 我来处理订单
	 */
	dealPurOrder : function() {
		this.main_win.creator.sendDataAndGetMes.createDelegate(this, [{
					ordersId : this.main_win.purchase_id_hidden.getValue()
				}])();
	},
	
	/**
	 * 根据采购面板得到表单信息并转换成字符串
	 * 
	 * @return {}
	 */
	getPurFormValues : function() {
		var form_values = this.purchase_panel.getForm().getValues();

		for (var j in form_values) {
			form_values[j] = castNoSelToNULL(form_values[j]);
		}

		form_values = Ext.util.JSON.encode(form_values);

		return form_values;
	},

	/**
	 * 批量插入采购记录
	 */
	purBatchInsert : function() {
		if (!batchValidateAlert(this.main_win.purchase_item_store, this.main_win.partner_combox)) {
			return;
		}
		var items = this.main_win.purchase_item_store.data.items;
		var records = getRecordPropValue(items);

		this.main_win.purchase_status_hidden.setValue(this.id == 'saveToTemp'
				+ this.main_win.versionCode ? '0' : '2');

		var form_values = this.main_win.creator.getPurFormValues
				.createDelegate(this.main_win)();

		this.main_win.creator.sendDataAndGetMes.createDelegate(this, [{
					'purOrder' : form_values,
					'purDetails' : Ext.util.JSON.encode(records)
				}])();

	},

	/**
	 * 批量修改采购记录
	 */
	purBatchUpdate : function() {

		if (!batchValidateAlert(this.main_win.purchase_item_store, this.main_win.partner_combox)) {
			return;
		}

		this.main_win.purchase_status_hidden.setValue(this.id == 'modifyToTemp'
				+ this.main_win.versionCode ? '0' : '2');

		var form_values = this.main_win.creator.getPurFormValues
				.createDelegate(this.main_win)();

		var obj = this.main_win.creator.getModifyData.createDelegate(this.main_win)();

		this.main_win.creator.sendDataAndGetMes.createDelegate(this, [{
					'pur' : form_values,
					// 'status' : this.id=='modifyToTemp' ? '0':'2',
					'all' : Ext.util.JSON.encode(obj.all),
					'add' : Ext.util.JSON.encode(obj.add),
					'update' : Ext.util.JSON.encode(obj.update)
				}])();

	},

	/**
	 * 返回
	 */
	purReturn : function() {
		this.main_win.close();
	},

	/**
	 * 新建下一张
	 * 
	 * @param {}
	 *            url
	 */
	purNewCreate : function() {
		// alert(this.url);
		var desktop = Uec3.App.getDesktop();   
		desktop.launchWindowByParam("addAutoPurchaseCreator",{});
//		this.main_win.creator.sendDataAndGetMes.bind(this, null)();
	},
	//
	// setDataItemsToComb : function(comb, items, label) {
	//
	// var record = getAreaRecord(label, 'id');
	// for (var i = 0; i < items.length; i++) {
	// comb.getStore().add(new record(items[i].data));
	// }
	//
	// },

	/**
	 * 放弃修改
	 * 
	 * @param {}
	 *            url
	 */
	purCancelModify : function() {
		this.main_win.creator.sendDataAndGetMes.createDelegate(this, [{
					ordersId : this.main_win.purchase_id_hidden.getValue()
				}])();
	},

	/**
	 * 删除订单
	 * 
	 * @param {}
	 *            url
	 */
	purDelete : function() {
		this.main_win.creator.sendDataAndGetMes.createDelegate(this, [{
					ordersId : this.main_win.purchase_id_hidden.getValue()
				}])();
	},

	/**
	 * 重新建立
	 */
	purCancelAndNewCreate : function() {
//		this.main_win.creator.purNewCreate.bind(this)();
		this.main_win.creator.sendDataAndGetMes.createDelegate(this, [null])();
	},

	/**
	 * 浏览订单
	 */
	purShowList : function() {
		// openByUrl(this.url, '单头浏览');
		var desktop = Uec3.App.getDesktop();
		desktop.launchWindowByParam("showPurchaseCreator", {});
	},
	
	takeOverOrders : function() {
		this.main_win.creator.sendDataAndGetMes.createDelegate(this, [{
					ordersId : this.main_win.purchase_id_hidden.getValue()
				}])();
	},
	
	takeOverUpdateOrSubmit : function() {
		if (!batchValidateAlert(this.main_win.purchase_item_store, this.main_win.partner_combox)) {
			return;
		}

		this.main_win.purchase_status_hidden.setValue(this.id == 'takeOverOrdersUpdate'
				+ this.main_win.versionCode ? '1' : '3');

		var form_values = this.main_win.creator.getPurFormValues
				.createDelegate(this.main_win)();

		var obj = this.main_win.creator.getModifyData.createDelegate(this.main_win)();

		this.main_win.creator.sendDataAndGetMes.createDelegate(this, [{
			'pur' : form_values,
			'all' : Ext.util.JSON.encode(obj.all),
			'add' : Ext.util.JSON.encode(obj.add),
			'update' : Ext.util.JSON.encode(obj.update)
		}])();

	}
});
